package com.wolfeyes.framework.service;

import com.wolfeyes.system.service.SysUserService;
import com.wolfeyes.system.domain.SysUser;
import com.wolfeyes.framework.springsecurity.domain.model.CustomizeUserDetails;
import com.wolfeyes.common.enums.UserStatus;
import com.wolfeyes.common.exception.BaseException;
import com.wolfeyes.common.utils.character.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @description 获取用户账号密码及权限信息
 * @title 自定义的系统登录用户服务层组件
 * @author yanyljava
 * @create 2020-09-05 13:03
 **/
@Slf4j
@Service
public class CustomizeUserDetailsService implements UserDetailsService {

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private SysPermissionService permissionService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//SysUser user = sysUserService.selectUserByUserName(username);
		SysUser sysUser = sysUserService.findByName(username);
		if (StringUtils.isNull(sysUser)) {
			log.info("登录用户：{} 不存在.", username);
			throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
		} else if (UserStatus.DELETED.getCode().equals(sysUser.getDelFlag())) {
			log.info("登录用户：{} 已被删除.", username);
			throw new BaseException("对不起，您的账号：" + username + " 已被删除");
		} else if (UserStatus.DISABLE.getCode().equals(sysUser.getStatus())) {
			log.info("登录用户：{} 已被停用.", username);
			throw new BaseException("对不起，您的账号：" + username + " 已停用");
		}

		return createLoginUser(sysUser);
	}

	public UserDetails createLoginUser(SysUser user) {
		
		return new CustomizeUserDetails(user, permissionService.getMenuPermission(user));
	}
}
